package edu.nuc.ahm.juc.procon;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * 线程之间的通信问题  生产者消费者问题 等待唤醒 通知唤醒
 * 线程交替执行 A B 操作同意变量 num = 0
 * A num+1
 * B num-1
 *
 * 判断等待 ， 业务， 通知
 *
 */
public class B {
    public static void main(String[] args) {
        Data data = new Data();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                     data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }

}

class Data2{  // 数字资源类
    private int num = 0;

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    // +1
    public  void increment() throws InterruptedException {

        // 取代了监视器
//        condition.await();
//        condition.signal();

        while (num!=0){
            //  等待消费
            condition.await();

        }
        num++;
        System.out.println(Thread.currentThread().getName()+"==>"+num);
        // 通知其他线程 我 +1 完毕了
        condition.signalAll();
    }

    // -1
    public  void decrement() throws InterruptedException {
        Condition condition = lock.newCondition();

        while (num==0){
            // 等待
            condition.await();
        }
        num--;
        System.out.println(Thread.currentThread().getName()+"==>"+num);
        // 通知其他线程 我 -1 完毕了
        condition.signalAll();
    }


}